﻿namespace ChinaUnicom.ViewModels
{
    using Avatar;
    using Avatar.Schedule;
    using ChinaUnicom.Controls;
    using ChinaUnicom.Models;
    using ChinaUnicom.Net;
    using ChinaUnicom.Tasks;
    using System;
    using System.ComponentModel;
    using System.Windows;

    public class ClientInformationContext : PageContext, INotifyPropertyChanged
    {
        ITaskScheduler scheduler;

        public ClientInformationContext()
        {
            ClientPullrefresh = "下拉可以刷新";
            ClientProgressEnabled = false;

            scheduler = SchedulerFactory.Create(SchedulerType.Serial);
            scheduler.Error += OnSchedulerError;
            scheduler.StateChanged += OnSchedulerStateChanged;

            ClientItems = Context.Current.Client.Items;

            // need to update.
            if (Context.Current.Product == null || Context.Current.Product.Started == DateTime.MinValue)
            {
                scheduler.Schedule(GenerateProductTask());
            }
            else
            {
                Product = Context.Current.Product;
            }
        }

        public void ForceUpdateClient()
        {
            if (NetHelper.Network.IsNetworkAvailable)
            {
                scheduler.Schedule(GenerateClientTask());
                scheduler.Schedule(GenerateProductTask());
            }
        }

        #region Tasks

        void OnSchedulerError(object sender, FailedEventArgs e)
        {
            Action<FailedEventArgs> action = args =>
            {
                Message.Tips(args.Exception.Message, "温馨提示");
            };

            action.UIThreadInvoke(e);
        }

        void OnSchedulerStateChanged(object sender, StateChangedArgs e)
        {
        }

        ITask GenerateAutologinTask()
        {
            ITask task = new AutologinTask();
            task.Failed += OnFailed;

            return task;
        }

        ITask GenerateClientTask()
        {
            if (!Authentication.Current.Signed)
            {
                scheduler.Schedule(GenerateAutologinTask());
            }

            ITask task = new ClientTask();
            task.Started += OnTaskStated;
            task.Failed += OnFailed;
            task.Completed += OnTaskCompleted;

            return task;
        }

        ITask GenerateProductTask()
        {
            if (!Authentication.Current.Signed)
            {
                scheduler.Schedule(GenerateAutologinTask());
            }

            ITask task = new ProductTask();
            task.Failed += OnFailed;
            task.Completed += OnTaskCompleted;

            return task;
        }

        void OnTaskStated(object sender, EventArgs e)
        {
            Action<ITask> action = task =>
            {
                ClientProgressEnabled = true;
            };

            action.UIThreadInvoke(sender as ITask);
        }

        void OnTaskCompleted(object sender, EventArgs e)
        {
            Action<ITask> action = task =>
            {
                switch (task.GetType().Name.ToLower())
                {
                    case "clienttask":
                        var c = task as ClientTask;
                        Context.Current.Client = c.Client;
                        ClientItems.Clear();
                        ClientItems.Add(Context.Current.Client.Items);
                        break;

                    case "producttask":
                        var p = task as ProductTask;
                        Context.Current.Product = p.Product;
                        Product = p.Product;
                        ClientProgressEnabled = false;
                        break;
                }
            };

            action.UIThreadInvoke(sender as ITask);
        }

        void OnFailed(object sender, FailedEventArgs e)
        {
            Action<FailedEventArgs> action = args =>
            {
                Message.Tips(args.Exception.Message, "温馨提示");
            };

            action.UIThreadInvoke(e);
        }

        #endregion

        ItemCollection clientItems;
        public ItemCollection ClientItems
        {
            get { return clientItems; }
            set
            {
                if (value != this.clientItems)
                {
                    clientItems = value;
                    NotifyPropertyChanged("ClientItems");
                }
            }
        }

        Product product;
        public Product Product
        {
            get { return product; }
            set
            {
                if (value != this.product)
                {
                    product = value;
                    NotifyPropertyChanged("Product");
                }
            }
        }

        bool clientProgressEnabled;
        public bool ClientProgressEnabled
        {
            get { return clientProgressEnabled; }
            set
            {
                if (value != clientProgressEnabled)
                {
                    clientProgressEnabled = value;
                    NotifyPropertyChanged("ClientProgressEnabled");
                }
            }
        }

        string clientPullrefresh;
        public string ClientPullrefresh
        {
            get { return clientPullrefresh; }
            set
            {
                if (value != clientPullrefresh)
                {
                    clientPullrefresh = value;
                    NotifyPropertyChanged("ClientPullrefresh");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
